<template>
  <div v-if="editOpen">
    <t-table :selected-row-keys="selectedRowKeys" @select-change="(val) => { selectedRowKeys = val }" rowKey="id"
      :data="data" :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #year="{ row }">
        <t-date-picker v-model="row.year" @change="() => { if (row.year !== '') { row.status = 'default' } }"
          :status="row.status" mode="year" clearable allow-input>
          <div slot="tips" v-if="row.status === 'error'">不能为空</div>
        </t-date-picker>
      </template>
      <template #benefit="{ row }">
        <t-input clearable @change="() => { if (row.benefit !== '') { row.status = 'default' } }" :status="row.status"
          v-model="row.benefit">
          <div slot="tips" v-if="row.status === 'error'">不能为空</div>
        </t-input>
      </template>
      <template #application="{ row }">
        <t-input clearable @change="() => { if (row.application !== '') { row.status = 'default' } }"
          :status="row.status" v-model="row.application">
          <div slot="tips" v-if="row.status === 'error'">不能为空</div>
        </t-input>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" :data="data" :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </t-table>
  </div>
</template>

<script>
import { getDictList } from "@/api/system/dict/data";

export default {
  name: "studioBenefits",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      dictTypes: {},
      selectedRowKeys: [],
      dialogOpen: false,
      header: '新增仪器设备',
      visible: true,
      formData: {
        sort: null,
        name: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        model: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        count: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        mainUse: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        addMethod: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        forex: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        rmb: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'year',
          title: "年度",
          align: "left",
          ellipsis: true
        },
        {
          colKey: 'benefit',
          title: "效益",
          align: "left",
          ellipsis: true
        },
        {
          colKey: 'application',
          title: "项目应用情况",
          align: "left",
          ellipsis: true
        },

      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'year',
          title: "年度",
          align: "left",
          ellipsis: true
        },
        {
          colKey: 'benefit',
          title: "效益",
          align: "left",
          ellipsis: true
        },
        {
          colKey: 'application',
          title: "项目应用情况",
          align: "left",
          ellipsis: true
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler (val) {
        const newData = this.data.map((val, index) => ({ ...val, sort: index + 1 }))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val.length > 0 && this.data.length <= 0) {
          this.data = val;
        }
      }
    },
  },
  async mounted () {
    await this.getDataTypes();
  },
  methods: {
    checkData () {
      const isValidate = this.data.every((val, index) => {
        if (val.name === "" || val.model === "" || val.count === "" || val.mainUse === "" || val.addMethod === "" || val.forex === "" || val.rmb === "" || val.name === "") {
          this.$set(this.data[index], 'status', 'error')
          this.$message.error(`仪器设备：第${index + 1}条内容不能为空`);
          return false;
        }
        this.$set(this.data[index], 'status', 'default')
        return true;
      });
      return isValidate;
    },
    addData () {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        name: ''
      })
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    getDataTypes () {
      return getDictList(["add_method"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
  }
}
</script>

<style lang="less" scoped>
//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}</style>
